package com.zzyl.nursing.service.impl;

import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.config.WebSocketServer;
import com.zzyl.nursing.domain.AlertData;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IAlertDataService;
import com.zzyl.nursing.vo.AlertNotifyVo;
import com.zzyl.system.mapper.SysUserRoleMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.AlertRuleMapper;
import com.zzyl.nursing.domain.AlertRule;
import com.zzyl.nursing.service.IAlertRuleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import javax.script.ScriptEngine;
import javax.script.ScriptException;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;

/**
 * 报警规则Service业务层处理
 *
 * @author 严佳保
 * @date 2025-10-20
 */
@Service
@Slf4j
public class AlertRuleServiceImpl extends ServiceImpl<AlertRuleMapper, AlertRule> implements IAlertRuleService {
    @Autowired
    private AlertRuleMapper alertRuleMapper;

    /**
     * 查询报警规则
     *
     * @param id 报警规则主键
     * @return 报警规则
     */
    @Override
    public AlertRule selectAlertRuleById(Long id) {
        return getById(id);
    }

    /**
     * 查询报警规则列表
     *
     * @param alertRule 报警规则
     * @return 报警规则
     */
    @Override
    public List<AlertRule> selectAlertRuleList(AlertRule alertRule) {
        return alertRuleMapper.selectAlertRuleList(alertRule);
    }

    /**
     * 新增报警规则
     *
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int insertAlertRule(AlertRule alertRule) {
        return save(alertRule) ? 1 : 0;
    }

    /**
     * 修改报警规则
     *
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int updateAlertRule(AlertRule alertRule) {
        return updateById(alertRule) ? 1 : 0;
    }

    /**
     * 批量删除报警规则
     *
     * @param ids 需要删除的报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除报警规则信息
     *
     * @param id 报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    @Autowired
    private StringRedisTemplate redisTemplate; //注意要和你放数据用的RedisTemplate要一致

    @Override
    public void alertFilter() {
        //查询所有规则
        List<AlertRule> list = this.list();
        //long count = count(Wrappers.<AlertRule>lambdaQuery().eq(AlertRule::getStatus, 1));
        //判断是否为空
        if (CollUtil.isEmpty(list)) {
            return;
        }
        //不为空 从redis获取数据
        List<Object> values = redisTemplate.boundHashOps(CacheConstants.IOT_DEVICE_LAST_DATA).values();
        //判断redis有没有数据
        if (CollUtil.isEmpty(values)) {
            return;
        }
        //不为空 循环遍历获取
        List<DeviceData> deviceDataList = new ArrayList<>();
        for (Object value : values) {
            deviceDataList.addAll(JSONUtil.toList(value.toString(), DeviceData.class));
        }
        //处理数据
        for (DeviceData deviceData : deviceDataList) {
            alterFilter(deviceData);
        }
    }

    private void alterFilter(DeviceData deviceData) {
        //查询报警规则
        //第一次查设备  查 status  iotid  functionId
        List<AlertRule> alertRuleList1 = list(Wrappers.<AlertRule>lambdaQuery()
                .eq(AlertRule::getStatus, 1)
                .eq(AlertRule::getIotId, deviceData.getIotId())
                .eq(AlertRule::getFunctionId, deviceData.getFunctionId()));
        //第二次查这个产品下的所有设备 status  -1  functionId
        List<AlertRule> alertRuleList2 = list(Wrappers.<AlertRule>lambdaQuery()
                .eq(AlertRule::getStatus, 1)
                .eq(AlertRule::getIotId, "-1")
                .eq(AlertRule::getFunctionId, deviceData.getFunctionId()));
        //合并两次查询的结果
        Collection<AlertRule> alertRuleList = CollUtil.addAll(alertRuleList1, alertRuleList2);
        //判断是否有规则
        if (CollUtil.isEmpty(alertRuleList)) {
            return;
        }
        //循环遍历结果
        for (AlertRule alertRule : alertRuleList) {
            deviceDataAlarmHandler(alertRule, deviceData);
        }
    }

    @Autowired
    private ScriptEngine scriptEngine;

    private void deviceDataAlarmHandler(AlertRule alertRule, DeviceData deviceData) {
        log.info("第四层校验的第一层...");
        String period = alertRule.getAlertEffectivePeriod();    //00:00:~ 23:59:59
        LocalTime startTime = LocalTime.parse(period.split("~")[0]);
        LocalTime endTime = LocalTime.parse(period.split("~")[1]);
        LocalTime localTime = deviceData.getAlarmTime().toLocalTime();
        //判断时间在不在startTime  endTime 之间
        if (localTime.isBefore(startTime) || localTime.isAfter(endTime)) {
            return;
        }
        log.info("第四层校验的第二层...");
        //拼凑一个表达式 上报的数据+运算符+阈值
        String expression = deviceData.getDataValue() + alertRule.getOperator() + alertRule.getValue();
        //计算表达式结果
        //上报的数据是否达到阈值
        boolean isReach = false;
        try {
            isReach = Boolean.parseBoolean(scriptEngine.eval(expression) + "");
        } catch (ScriptException e) {
            e.printStackTrace();
            isReach = false;
        }
//        String alertCountKey = CacheConstants.ALERT_TRIGGER_COUNT_PREFIX + deviceData.getIotId() +
//                deviceData.getProductKey() + alertRule.getFunctionId() + alertRule.getId();
//
//        String slientKey = CacheConstants.ALERT_SILENT_PREFIX + deviceData.getIotId() +
//                deviceData.getProductKey() + alertRule.getFunctionId() + alertRule.getId();

        String alertCountKey = CacheConstants.ALERT_TRIGGER_COUNT_PREFIX + deviceData.getIotId() + deviceData.getProductKey() + alertRule.getFunctionId() + alertRule.getId();
        String slientKey = CacheConstants.ALERT_SILENT_PREFIX + deviceData.getIotId() + deviceData.getProductKey() + alertRule.getFunctionId() + alertRule.getId();
        if (!isReach) {
            //删除报警数
            redisTemplate.delete(alertCountKey);
            return;
        }
        log.info("第四层校验的三层....");
        //判断是否有物模型
        if (redisTemplate.hasKey(slientKey)) {
            return;
        }
        log.info("第四层校验的四层...");

        Long count = redisTemplate.boundValueOps(alertCountKey).increment(1);
        if (alertRule.getDuration() > count) {
            return;
        }
        //达到报警规则
        //先删报警数
        redisTemplate.delete(alertCountKey);
        //再添加沉默周期
        redisTemplate.boundValueOps(slientKey).set("", alertRule.getAlertSilentPeriod(), TimeUnit.MINUTES);


        log.info("校验全部通过");
        //插入报警数据
        insertAlertData(alertRule, deviceData);
    }

    @Value("${alert.deviceMaintainerRole}")
    private String deviceMaintainerRole;

    @Value("${alert.managerRole}")
    private String managerRole;

    @Autowired
    private IAlertDataService alertDataService;
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    private void insertAlertData(AlertRule alertRule, DeviceData deviceData) {
        //查人 判断上传数据是否是老人数据
        List<Long> userIds = List.of();
        if (deviceData.getLocationType().equals(0)) {
            //0 说明是随身设备  找管理员
            userIds = deviceMapper.selectNursingIdsByIotIdWithElder(deviceData.getIotId());
        } else {
            //判断 在房间还在是床位
            if (deviceData.getPhysicalLocationType().equals(1)) {
                userIds = sysUserRoleMapper.selectUserIdByRoleName(deviceMaintainerRole);
            } else if (deviceData.getPhysicalLocationType().equals(2)) {
                userIds = deviceMapper.selectNursingIdsByIotIdWithBed(deviceData.getIotId());
            }
        }
        //上报超级管理员
        List<Long> adminIds = sysUserRoleMapper.selectUserIdByRoleName(managerRole);
        //合并
        Collection<Long> collection = CollUtil.addAll(userIds, adminIds);
        //去重
        userIds = CollUtil.distinct(collection);

        List<AlertData> alertDataList = new ArrayList<>();
        for (Long userId : userIds) {
            AlertData alertData = new AlertData();
            alertData.setIotId(deviceData.getIotId());
            alertData.setDeviceName(deviceData.getDeviceName());
            alertData.setProductKey(deviceData.getProductKey());
            alertData.setProductName(deviceData.getProductName());
            alertData.setFunctionId(deviceData.getFunctionId());
            alertData.setAccessLocation(deviceData.getAccessLocation());
            alertData.setLocationType(deviceData.getLocationType());
            alertData.setPhysicalLocationType(deviceData.getPhysicalLocationType());
            alertData.setDeviceDescription(deviceData.getDeviceDescription());
            alertData.setDataValue(deviceData.getDataValue());
            alertData.setAlertRuleId(alertRule.getId());  //规则的id
            alertData.setAlertReason(deviceData.getFunctionId() + alertRule.getOperator() + alertRule.getValue() + alertRule.getDuration() + alertRule.getAlertSilentPeriod());  //报警原因  报警原因，格式：功能名称+运算符+阈值+持续周期+沉默周期
            alertData.setType(alertRule.getAlertDataType());  //报警数据类型，0：老人异常数据，1：设备异常数据
            alertData.setStatus(0); //0：待处理，1：已处理
            alertData.setUserId(userId);

            alertDataList.add(alertData);
        }
        alertDataService.saveBatch(alertDataList);

        // 发送websocket消息
        log.info("🎯 进入通知方法，准备调用WebSocket通知");
        websocketNotity(alertDataList.get(0), alertRule, userIds);
    }

    @Autowired
    private WebSocketServer webSocketServer;

    private void websocketNotity(AlertData alertData, AlertRule alertRule, Collection<Long> userIds) {
        AlertNotifyVo alertNotifyVo = BeanUtil.toBean(alertData, AlertNotifyVo.class);
        alertNotifyVo.setAccessLocation(alertData.getRemark());
        alertNotifyVo.setFunctionName(alertRule.getFunctionName());
        alertNotifyVo.setAlertDataType(alertRule.getAlertDataType());
        alertNotifyVo.setNotifyType(1);
        webSocketServer.sendMessageToConsumer(alertNotifyVo, userIds);

    }


}
